/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.api.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.server.modules.api.vo.easemob.Credential;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;

import java.util.Date;

import com.server.common.persistence.DataEntity;
import org.hibernate.validator.constraints.Length;

/**
 * 环信tokenEntity
 * @author 王磊
 * @version 2016-08-15
 */
public class TEmToken extends DataEntity<TEmToken> {
	
	private static final long serialVersionUID = 1L;
	private String accessToken;		// 环信token
	private Date createTime;		// create_time
	private Long expiredAt;		// expired_at

	public TEmToken() {
		super();
	}

	public TEmToken(String accessToken,Long expiredAt){
		super();
		this.accessToken = accessToken;
		this.expiredAt = expiredAt;
		this.createTime = new Date();
	}

	public TEmToken(String id){
		super(id);
	}

	@Length(min=0, max=255, message="环信token长度必须介于 0 和 255 之间")
	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	
	public Long getExpiredAt() {
		return expiredAt;
	}

	public void setExpiredAt(Long expiredAt) {
		this.expiredAt = expiredAt;
	}


	public static void applyAuthentication(HttpEntityEnclosingRequestBase httpMethodEntity, Credential credentail) {
		applyAuthentication(httpMethodEntity, credentail.getToken());
	}

	public static void applyAuthentication(HttpEntityEnclosingRequestBase httpMethodEntity, TEmToken token) {
		httpMethodEntity.addHeader("Authorization", "Bearer " + token.getAccessToken());
	}

	public static void applyAuthentication(HttpRequestBase httpMethodEntity, Credential credentail) {
		applyAuthentication(httpMethodEntity, credentail.getToken());
	}

	public static void applyAuthentication(HttpRequestBase httpMethodEntity, TEmToken token) {
		//TODO 以前是  token.toString()
		httpMethodEntity.addHeader("Authorization", "Bearer " + token.getAccessToken());
	}

	public boolean isExpired() {
		return System.currentTimeMillis() > expiredAt;
	}


}